<template>
  <div class="center_bottom" :class="{ fullscreen: isFullscreen }" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">
    <div class="chart-controls">
      <button v-for="option in chartOptions" :key="option.value" :class="['chart-btn', { active: selectedChart === option.value }]" @click="selectChart(option.value)">
        {{ option.label }}
      </button>
    </div>

    <!-- 放大/缩小按钮 -->
    <!-- <div class="zoom-controls">
      <button 
        v-if="!isFullscreen"
        class="zoom-btn zoom-in-btn"
        title="全屏显示"
        @click="toggleFullscreen"
      >
        <svg class="zoom-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M21 21L16.514 16.506M19 10.5C19 15.194 15.194 19 10.5 19S2 15.194 2 10.5 5.806 2 10.5 2 19 5.806 19 10.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
          <path d="M13.5 10.5H7.5M10.5 7.5V13.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
        </svg>
        <span class="zoom-text">全屏</span>
      </button>
      <button 
        v-if="isFullscreen"
        class="zoom-btn zoom-out-btn"
        title="退出全屏"
        @click="toggleFullscreen"
      >
        <svg class="zoom-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M21 21L16.514 16.506M19 10.5C19 15.194 15.194 19 10.5 19S2 15.194 2 10.5 5.806 2 10.5 2 19 5.806 19 10.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
          <path d="M13.5 10.5H7.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
        </svg>
        <span class="zoom-text">退出</span>
      </button>
    </div> -->

    <!-- F11键提示信息 -->
    <!-- <div 
      v-if="showF11Tip && isMouseOver" 
      class="f11-tip"
      :class="{ 'fullscreen-tip': isFullscreen }"
    >
      {{ isFullscreen ? '按F11键退出全屏' : '按F11键进入全屏' }}
    </div> -->

    <div v-if="pageflag" class="echarts_bottom">
      <Echart ref="deformationChart" :options="chartData" :height="'100%'" />
    </div>
    <Reacquire v-else line-height="200px" @onclick="getData"> 重新获取 </Reacquire>
  </div>
</template>

<script>
import Echart from "@/components/xing-bian-screen/echart/index.vue";
import Reacquire from "@/components/xing-bian-screen/reacquire/reacquire.vue";
import { getDeformCurveList } from "@/api/xing-bian-screen/deformation-api.js";
import tokenManager from "@/utils/tokenManager";

export default {
  name: "CenterBottom",
  components: {
    Echart,
    Reacquire
  },
  props: {
    radarId: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      pageflag: true,
      timer: null,
      isFullscreen: false, // 全屏状态
      isMouseOver: false, // 鼠标悬停状态
      showF11Tip: true, // 是否显示F11提示
      chartOptions: [
        { value: 0, label: "形变曲线(mm)" },
        { value: 1, label: "速度曲线(mm/h)" },
        { value: 2, label: "加速度曲线(mm/h²)" }
      ],
      selectedChart: 0, // 默认选择形变曲线
      chartData: {},
      rawData: [], // 存储原始API数据
      selectedPoints: [], // 存储选中的监测点信息（包含颜色）
      monitoringPointsColors: {}, // 存储监测点颜色映射
      defaultData: {
        xAxis: [],
        series: []
      }
    };
  },
  computed: {
    selectPointKey() {
      return this.$store.state["xing-bian-screen-setting"].selectPointKey;
    }
  },
  watch: {
    radarId: {
      handler(newRadarId) {
        if (newRadarId) {
          this.getData();
        }
      },
      immediate: false
    },
    selectPointKey: {
      handler(list) {
        if (!list.length) {
          // console.log("监测点选择为空");
          // this.initDefaultData();
        }
      },
      immediate: true
    }
  },
  created() {
    this.initDefaultData();
    this.getData();

    // 监听监测点选择事件
    this.$root.$on("monitoring-point-selected", this.handlePointSelection);

    // 监听右中组件的数据刷新事件，同步选中状态
    this.$root.$on("monitoring-points-refreshed", this.syncSelectedPoints);

    // 设置定时器，每60秒刷新一次数据
    this.timer = setInterval(() => {
      this.getData();
    }, 60000);
  },
  mounted() {
    // 添加F11键监听
    document.addEventListener("keydown", this.handleKeyDown);
  },
  // beforeDestroy() {
  //   // 清除定时器
  //   if (this.timer) {
  //     clearInterval(this.timer);
  //     this.timer = null;
  //   }

  //   // 移除事件监听
  //   this.$root.$off('monitoring-point-selected', this.handlePointSelection);
  //   this.$root.$off('monitoring-points-refreshed', this.syncSelectedPoints);
  // },

  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }

    // 移除事件监听
    this.$root.$off("monitoring-point-selected", this.handlePointSelection);
    this.$root.$off("monitoring-points-refreshed", this.syncSelectedPoints);

    // // 移除全屏事件监听
    // document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
    // document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange);
    // document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange);
    // document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange);

    // // 移除F11键监听
    // document.removeEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    // 初始化默认数据
    initDefaultData() {
      // 生成24小时时间轴
      const timeData = [];
      for (let i = 0; i < 24; i++) {
        timeData.push(i.toString().padStart(2, "0") + ":00");
      }

      this.defaultData = {
        xAxis: timeData,
        series: [
          {
            name: "暂无数据",
            type: "line",
            data: Array(24).fill(0),
            lineStyle: { width: 0, opacity: 0 },
            itemStyle: { opacity: 0 },
            symbol: "none"
          }
        ]
      };
      // this.chartData.series = [];
      // this.chartData.xAxis = this.defaultData.xAxis;
      this.updateChartOptions();
    },

    // 获取形变曲线数据
    async getData() {
      try {
        // 检查token有效性
        if (!tokenManager.isTokenValid()) {
          console.warn("Token无效，跳过数据请求");
          return;
        }

        // 如果没有选中的监测点，清空图表数据
        if (this.selectedPoints.length === 0) {
          this.setDefaultData();
          return;
        }

        // 设置时间范围（昨天的数据）
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        const startTime = yesterday.getFullYear() + "-" + (yesterday.getMonth() + 1).toString().padStart(2, "0") + "-" + yesterday.getDate().toString().padStart(2, "0") + " 00:00:00";
        const endTime = yesterday.getFullYear() + "-" + (yesterday.getMonth() + 1).toString().padStart(2, "0") + "-" + yesterday.getDate().toString().padStart(2, "0") + " 23:59:59";

        const params = {
          kind: this.selectedChart,
          radarId: this.radarId,
          index: this.selectedPoints.map(p => p.pointIndex), // 提取pointIndex数组
          startTime: startTime,
          endTime: endTime
        };
        console.log(params, 2222222222);

        const response = await getDeformCurveList(params);

        if (response && response.code === 200 && response.data) {
          this.rawData = response.data;
          this.processChartData();
          this.pageflag = true;
        } else {
          console.warn("获取形变曲线数据失败:", response);
          this.pageflag = false;
        }
      } catch (error) {
        console.error("获取形变曲线数据出错:", error);
        this.setDefaultData();
      }
    },

    // 处理图表数据
    processChartData1() {
      // 固定显示两条线，不再根据监测点数据生成
      const timeData = [];
      for (let i = 0; i < 24; i++) {
        timeData.push(i.toString().padStart(2, "0") + ":00");
      }

      const series = [
        {
          name: "底部线",
          type: "line",
          data: Array(24).fill(0),
          lineStyle: {
            color: "#00CCFF",
            width: 2
          },
          itemStyle: {
            color: "#00CCFF"
          },
          symbol: "circle",
          symbolSize: 4
        },
        {
          name: "顶部线",
          type: "line",
          data: Array(24).fill(1),
          lineStyle: {
            color: "#FF6B6B",
            width: 2
          },
          itemStyle: {
            color: "#FF6B6B"
          },
          symbol: "circle",
          symbolSize: 4
        }
      ];

      this.chartData = {
        xAxis: timeData,
        series: series
      };

      this.updateChartOptions();
    },

    // 处理图表数据
    processChartData() {
      if (!this.rawData || !this.rawData.list) {
        this.setDefaultData();
        return;
      }

      // 从API返回的数据中提取时间和数据点
      const pointsData = this.rawData.list;
      const series = [];

      // 遍历每个监测点的数据
      Object.keys(pointsData).forEach((pointId, index) => {
        const pointData = pointsData[pointId];

        if (!pointData || pointData.length === 0) {
          return;
        }

        // 提取时间和数值数据
        const timeData = [];
        const valueData = [];

        pointData.forEach(item => {
          // 解析时间，转换为本地时间格式
          const time = new Date(item.t);
          const timeStr = time.getHours().toString().padStart(2, "0") + ":" + time.getMinutes().toString().padStart(2, "0");
          timeData.push(timeStr);

          // 处理数值，根据文档说明需要除以100
          const value = parseFloat(item.v) / 100;
          valueData.push(value.toFixed(3));
        });

        // 获取对应监测点的颜色，如果没有则使用默认颜色
        const pointColor = this.monitoringPointsColors[pointId] || this.getPointColor(index);

        // 查找对应的监测点名称
        const selectedPoint = this.selectedPoints.find(p => p.pointIndex == pointId);
        const pointName = selectedPoint ? selectedPoint.name : `监测点${pointId}`;

        // 创建系列数据
        series.push({
          name: pointName,
          type: "line",
          smooth: true,
          data: valueData,
          itemStyle: {
            color: pointColor
          },
          lineStyle: {
            color: pointColor,
            width: 2
          }
        });
      });

      // 如果有数据，使用第一个监测点的时间轴
      let xAxisData = [];
      if (series.length > 0) {
        const firstPointData = pointsData[Object.keys(pointsData)[0]];
        if (firstPointData && firstPointData.length > 0) {
          xAxisData = firstPointData.map(item => {
            const time = new Date(item.t);
            return time.getHours().toString().padStart(2, "0") + ":" + time.getMinutes().toString().padStart(2, "0");
          });
        }
      }

      // 如果没有数据，使用默认24小时时间轴
      if (xAxisData.length === 0) {
        for (let i = 0; i < 24; i++) {
          xAxisData.push(i.toString().padStart(2, "0") + ":00");
        }
      }

      this.chartData = {
        xAxis: xAxisData,
        series: series
      };

      this.updateChartOptions();
    },

    // 设置默认数据
    setDefaultData() {
      this.chartData = this.defaultData;
      this.updateChartOptions();
      this.pageflag = true;
    },

    // 获取监测点颜色
    getPointColor(index) {
      const colors = ["#00CCFF", "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8"];
      return colors[index % colors.length];
    },

    // 处理监测点选择
    handlePointSelection(point) {
      if (point.selected) {
        // 添加监测点信息，包含颜色
        const existingIndex = this.selectedPoints.findIndex(p => p.pointIndex === point.pointIndex);
        if (existingIndex === -1) {
          this.selectedPoints.push({
            pointIndex: point.pointIndex,
            name: point.name,
            color: point.color
          });
        }
        // 更新颜色映射
        this.monitoringPointsColors[point.pointIndex] = point.color;
      } else {
        // 移除监测点
        this.selectedPoints = this.selectedPoints.filter(p => p.pointIndex !== point.pointIndex);
        delete this.monitoringPointsColors[point.pointIndex];
      }

      // 重新获取数据
      this.getData();
    },

    // 选择图表类型
    selectChart(value) {
      this.selectedChart = value;
      // 重新获取数据
      this.getData();
    },

    // 同步选中的监测点状态
    syncSelectedPoints(monitoringPoints) {
      // 根据右中组件的监测点状态更新selectedPoints和颜色映射
      this.selectedPoints = [];
      this.monitoringPointsColors = {};

      monitoringPoints.forEach(point => {
        if (point.selected && point.pointIndex) {
          this.selectedPoints.push({
            pointIndex: point.pointIndex,
            name: point.name,
            color: point.color
          });
          this.monitoringPointsColors[point.pointIndex] = point.color;
        }
      });

      // 重新获取数据（如果没有选中的点会自动清空图表）
      this.getData();
    },

    // 更新Echarts选项
    updateChartOptions() {
      // 根据选择的曲线类型设置Y轴单位
      let yAxisName = "";
      switch (this.selectedChart) {
        case 0:
          yAxisName = "形变 (mm)";
          break;
        case 1:
          yAxisName = "速度 (mm/h)";
          break;
        case 2:
          yAxisName = "加速度 (mm/h²)";
          break;
      }

      const series = this.chartData.series || this.defaultData.series;
      const xAxisData = this.chartData.xAxis || this.defaultData.xAxis;

      this.chartData = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross"
          },
          backgroundColor: "rgba(0, 40, 77, 0.8)",
          borderColor: "#0177D4",
          textStyle: {
            color: "#FFFFFF"
          }
        },
        legend: {
          data: series.map(s => s.name),
          textStyle: {
            color: "#B4B4B4"
          },
          top: 10
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "15%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: "#0177D4"
            }
          },
          axisLabel: {
            color: "#B4B4B4"
          }
        },
        yAxis: {
          type: "value",
          name: yAxisName,
          min: 0,
          max: 1,
          splitNumber: 1,
          nameTextStyle: {
            color: "#B4B4B4"
          },
          axisLine: {
            lineStyle: {
              color: "#0177D4"
            }
          },
          axisLabel: {
            color: "#B4B4B4",
            formatter: "{value}"
          },
          splitLine: {
            lineStyle: {
              color: "rgba(1, 119, 212, 0.3)"
            }
          }
        },
        series: series
      };
    },

    // 切换全屏状态
    toggleFullscreen() {
      if (!this.isFullscreen) {
        // 进入全屏
        this.enterFullscreen();
      } else {
        // 退出全屏
        this.exitFullscreen();
      }
    },

    // 进入全屏
    enterFullscreen() {
      const element = this.$el;

      // 设置全屏状态
      this.isFullscreen = true;

      // 使用浏览器全屏API
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      }

      // 监听全屏状态变化
      document.addEventListener("fullscreenchange", this.handleFullscreenChange);
      document.addEventListener("webkitfullscreenchange", this.handleFullscreenChange);
      document.addEventListener("mozfullscreenchange", this.handleFullscreenChange);
      document.addEventListener("MSFullscreenChange", this.handleFullscreenChange);

      // 全屏后重新渲染图表
      this.$nextTick(() => {
        setTimeout(() => {
          if (this.$refs.deformationChart) {
            this.$refs.deformationChart.resize();
          }
        }, 100);
      });
    },

    // 退出全屏
    exitFullscreen() {
      this.isFullscreen = false;

      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    },

    // 处理全屏状态变化
    handleFullscreenChange() {
      const isCurrentlyFullscreen = !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement);

      if (!isCurrentlyFullscreen && this.isFullscreen) {
        // 用户通过ESC键或其他方式退出全屏
        this.isFullscreen = false;

        // 移除事件监听
        document.removeEventListener("fullscreenchange", this.handleFullscreenChange);
        document.removeEventListener("webkitfullscreenchange", this.handleFullscreenChange);
        document.removeEventListener("mozfullscreenchange", this.handleFullscreenChange);
        document.removeEventListener("MSFullscreenChange", this.handleFullscreenChange);

        // 重新渲染图表
        this.$nextTick(() => {
          setTimeout(() => {
            if (this.$refs.deformationChart) {
              this.$refs.deformationChart.resize();
            }
          }, 100);
        });
      }
    },

    // 处理遮罩层点击
    handleOverlayClick() {
      this.exitFullscreen();
    },

    // 处理鼠标进入事件
    handleMouseEnter() {
      this.isMouseOver = true;
    },

    // 处理鼠标离开事件
    handleMouseLeave() {
      this.isMouseOver = false;
    },

    // 处理F11键按下事件
    handleKeyDown(event) {
      // 只有当鼠标在曲线图区域内时才响应F11键
      if (event.key === "F11" && this.isMouseOver) {
        event.preventDefault(); // 阻止浏览器默认的F11全屏行为
        this.toggleFullscreen();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.center_bottom {
  width: 100%;
  height: 100%;
  position: relative;

  .chart-controls {
    display: flex;
    justify-content: center;
    padding: 10px 0;

    .chart-btn {
      margin: 0 5px;
      padding: 5px 15px;
      background: rgba(1, 119, 212, 0.2);
      border: 1px solid #0177d4;
      border-radius: 4px;
      color: #b4b4b4;
      cursor: pointer;
      font-size: 12px;
      transition: all 0.3s;

      &:hover {
        background: rgba(1, 119, 212, 0.4);
        color: #ffffff;
      }

      &.active {
        background: #0177d4;
        color: #ffffff;
      }
    }
  }

  .echarts_bottom {
    width: 100%;
    height: calc(100% - 50px);
  }
}
</style>

<style lang="scss" scoped>
.center_bottom {
  width: 100%;
  height: 100%;
  position: relative;

  .chart-controls {
    display: flex;
    justify-content: center;
    padding: 10px 0;

    .chart-btn {
      margin: 0 5px;
      padding: 5px 15px;
      background: rgba(1, 119, 212, 0.2);
      border: 1px solid #0177d4;
      border-radius: 4px;
      color: #b4b4b4;
      cursor: pointer;
      font-size: 12px;
      transition: all 0.3s;

      &:hover {
        background: rgba(1, 119, 212, 0.4);
        color: #ffffff;
      }

      &.active {
        background: #0177d4;
        color: #ffffff;
      }
    }
  }

  .zoom-controls {
    position: absolute;
    top: 15px;
    right: 15px;
    z-index: 10;

    .zoom-btn {
      min-width: 80px;
      height: 36px;
      background: linear-gradient(135deg, rgba(1, 119, 212, 0.9), rgba(0, 150, 255, 0.9));
      border: none;
      border-radius: 20px;
      color: #ffffff;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      font-size: 12px;
      font-weight: 500;
      padding: 0 16px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 4px 12px rgba(1, 119, 212, 0.3);
      backdrop-filter: blur(10px);

      .zoom-icon {
        width: 16px;
        height: 16px;
        flex-shrink: 0;
      }

      .zoom-text {
        font-size: 12px;
        line-height: 1;
        white-space: nowrap;
      }

      &:hover {
        background: linear-gradient(135deg, #0177d4, #0096ff);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(1, 119, 212, 0.4);
      }

      &:active {
        transform: translateY(0);
        box-shadow: 0 2px 8px rgba(1, 119, 212, 0.3);
      }
    }
  }

  .echarts_bottom {
    width: 100%;
    height: calc(100% - 50px);
  }

  // F11提示样式
  .f11-tip {
    position: absolute;
    top: 60px;
    right: 15px;
    background: rgba(0, 0, 0, 0.8);
    color: #ffffff;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 1000;
    white-space: nowrap;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);

    &.fullscreen-tip {
      top: 70px;
      right: 20px;
      z-index: 10001;
    }
  }

  // 全屏样式
  &.fullscreen {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9999 !important;
    background: rgba(0, 40, 77, 0.95) !important;

    .chart-controls {
      position: absolute;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 10000;
    }

    .zoom-controls {
      top: 20px;
      right: 20px;
      z-index: 10000;
    }

    .echarts_bottom {
      width: 100% !important;
      height: calc(100vh - 80px) !important;
      padding: 60px 20px 20px 20px;
    }

    // 隐藏全屏遮罩层相关样式，因为现在使用浏览器原生全屏
    .fullscreen-overlay {
      display: none;
    }
  }
}
</style>
